/**
 * 
 */
package com.googolmo.NowPlaying.Service;

import java.util.Date;

import com.googolmo.NowPlaying.MusicNotification;
import com.googolmo.NowPlaying.NPUtils;
import com.googolmo.NowPlaying.NowPlayingApplication;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.googolmo.NowPlaying.Constant;
import com.googolmo.NowPlaying.Receiver.MusicReceiver;
import com.googolmo.NowPlaying.SharePreferences.MusicPreferences;

/**
 * @author user
 * 
 */
public class MusicService extends Service {

	// private NotificationManager nm;
	// private Notification notification;
	private String description;
	private String message;
	private String subject;
	private Bundle bundle;

	private Long id;
	private String artist;
	private String album;
	private String track;
	private int domain;

	// private Intent pIntent;
	// private PendingIntent pendingIntent;

	// private static MusicService mService;

	private MusicReceiver receiver;
	private static MusicService mService;

	private Handler handler = new Handler();

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			if (NPUtils.isServiceRunning(getApplicationContext(),
					Constant.MUSIC_SERVICE_NAME) == false) {
				// deleteNotification();
				stopService(MusicService.this);
			}
		}
	};

	/**
	 * 获得服务实例
	 * 
	 * @return
	 */
	public static MusicService getInstance() {
		if (mService == null) {
			mService = new MusicService();
		}
		return mService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(Constant.TAG, "bind service");
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(Constant.TAG, "on create");
		receiver = new MusicReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		this.registerReceiver(receiver, filter);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// nm = null;
		message = "";
		subject = "";
		try {
			this.unregisterReceiver(receiver);
			handler.removeCallbacks(runnable);
		} catch (Exception e) {
			e.printStackTrace();
		}
		MusicPreferences.setHandsetPlug(this, 0);
		MusicNotification.deleteNotification(getApplicationContext());
		Log.d(Constant.TAG, "destrtoy");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Log.d(Constant.TAG, "start service");
		MusicPreferences.setHandsetPlug(this, 2);
		if (intent.getAction().equals(Constant.META_CHANGED)) {

			// TODO 播放时间和信息比较
			String des = getMusicInfo(intent);
			if (des != null) {
				if (!NowPlayingApplication.getInstance().getLastPlayInfo()
						.equalsIgnoreCase(des)
						|| NPUtils.compareTime(
								((NowPlayingApplication) (getApplication()))
										.getLastPlayTime(),
								new Date(System.currentTimeMillis())) > 2000) {
					if (NPUtils.isServiceRunning(getApplicationContext(),
							Constant.MUSIC_SERVICE_NAME)) {
						((NowPlayingApplication) (getApplication()))
								.setLastPlayInfo(des);
						((NowPlayingApplication) (getApplication()))
								.setLastPlayTime(new Date(System
										.currentTimeMillis()));
						setNotification();
					} else {
						// deleteNotification();
						stopService(this);
					}
				} else {
					// stopService(this);
				}

			} else {
				stopService(this);
			}

		} else if (intent.getAction().equals(Constant.PLAYSTATE_CHANGED)) {
			Log.d(Constant.TAG, Constant.PLAYSTATE_CHANGED);

			if (NPUtils.isServiceRunning(getApplicationContext(),
					Constant.MUSIC_SERVICE_NAME) == true) {
				// setNotification(intent);
				handler.postDelayed(runnable, 30000);
			} else {
				// deleteNotification();
				// stopService(this);
			}

			String des = getMusicInfo(intent);
			if (des != null) {

				((NowPlayingApplication) (getApplication()))
						.setLastPlayInfo(des);
				((NowPlayingApplication) (getApplication()))
						.setLastPlayTime(new Date(System.currentTimeMillis()));
				setNotification();
			} else {
				stopService(this);
			}

		}
		// else if (intent.getAction().equals(Constant.DELETE_NOTIFICATION)) {
		// deleteNotification();
		// handler.removeCallbacks(runnable);
		// stopService(this);
		// }

	}

	// public void deleteNotification() {
	// if (nm != null) {
	// nm.cancelAll();
	// }
	// }

	// public void stopService() {
	// getApplicationContext().stopService(
	// new Intent(this, MusicService.class));
	// }

	private String getMusicInfo(Intent intent) {
		bundle = intent.getExtras();

		id = null;
		artist = null;
		album = null;
		track = null;
		domain = -1;

		try {
			id = bundle.getLong("id");
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(Constant.TAG, "id is null");
			id = -1L;
		}
		try {
			artist = bundle.getString("artist");
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(Constant.TAG, "artist is null");
			artist = "";
		}
		try {
			album = bundle.getString("album");
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(Constant.TAG, "album is null");
			album = "";
		}
		try {
			track = bundle.getString("track");
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(Constant.TAG, "track is null");
			track = "";
		}
		try {
			domain = bundle.getInt("domain");
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(Constant.TAG, "domain is null");
			domain = -1;
		}
		message = null;
		description = null;
		if (track != null && track.length() > 0) {
			message = "I am #NowPlaying ♪" + track;
			description = track;
			if (artist != null && artist.length() > 0) {
				message = message + " By: #" + getArtist(artist);
				description += " - " + artist;
			}
			if (album != null && album.length() > 0) {
				message = message + " From:" + album;
				description += " - " + album;
			}
		}

		// message = "I am #NowPlaying ♪" + track + " By: #" + getArtist(artist)
		// +
		subject = "";
		return description;
	}

	public void setNotification() {

		if (MusicPreferences.getIsToast(MusicService.this)) {
			Toast.makeText(getApplicationContext(), description,
					Toast.LENGTH_SHORT).show();
		}

		Log.d(Constant.TAG, artist + "-" + album + "-" + track + "-" + id + "-"
				+ domain);

		MusicNotification.setNofication(getApplicationContext(), description,
				subject, message);
	}

	private String getArtist(String artist) {
		if (artist != null) {
			return artist.replaceAll(" ", "_");
		} else {
			return artist;
		}

	}

	/**
	 * 启动服务
	 * 
	 * @param context
	 * @param service
	 */
	public static void startService(Context context, Intent service) {
		context.startService(service);
	}

	/**
	 * 结束服务
	 * 
	 * @param service
	 */
	public static void stopService(Service service) {
		service.stopSelf();
	}

}
